package afcp.alumni.dao.base;

import javax.annotation.Resource;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)
class PM {

	@Autowired
	@Resource(name="persistenceManagerFactoryProxy")
	private PersistenceManagerFactory pmfInstance;
//	protected static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");
//	protected PersistenceManager persistenceManager = PersistenceManagerFactoryUtils.getPersistenceManager(pmfInstance, true);
	//pmfInstance.getPersistenceManager()
	
	private PersistenceManager pm = null;
	synchronized PersistenceManager getPm() {
		if (pm == null || pm.isClosed()) {
//			pm = PersistenceManagerFactoryUtils.getPersistenceManager(pmfInstance, true);
			pm = pmfInstance.getPersistenceManager();
		}
		return pm;
//		return pmfInstance.getPersistenceManager();
	}
	
	void resetPm() {
		if (pm != null) {
			pm.close();
		}
		pm = null;
	}
	
	@Override
	protected void finalize() throws Throwable {
		pm.close();
		super.finalize();
	}

}
